package controllers;

import java.util.List;

import models.Post;
import models.Setting;
import play.cache.Cache;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.libs.Codec;
import play.libs.Images;
import play.mvc.Before;
import play.mvc.Controller;

public class Application extends Controller {

	@Before
	static void globals() {
		renderArgs.put("web", Setting.find("order by id desc").first());
	}

	public static void index() {
		Post frontPost = Post.find("status = true order by addTime desc")
				.first();
		List<Post> olderPosts = Post
				.find("status = true order by addTime desc").from(1).fetch(10);
		render(frontPost, olderPosts);
	}

	public static void show(Long id) {
		Post post = Post.findById(id);
		String randomID = Codec.UUID();
	    render(post, randomID);
	}

	public static void postComment
	(
			Long postId, 
			@Required(message="名字不能为空!") String author, 
			String url, 
			@Required(message="评论内容不能为空!") String content,
			@Required(message="请输入验证码!") String code,
			String randomID
	) {
		Post post = Post.findById(postId);
		validation.equals(code, Cache.get(randomID)).message("验证码有误，请重新输入!");
		if (Validation.hasErrors()) {
			render("Application/show.html", post);
		}
		post.addComment(author, url, content);
		flash.success("多谢您的评论 %s", author);
		show(postId);
	}
	
	public static void captcha(String id) {
	    Images.Captcha captcha = Images.captcha();
	    String code = captcha.getText("#1B3266");
	    Cache.set(id, code, "10mn");
	    renderBinary(captcha);
	}
	
	public static void listTagged(String tag) {
	    List<Post> posts = Post.findTaggedWith(tag);
	    render(tag, posts);
	}
}